package com.bestcem.xm.txtanls.grpc.service.param;

import com.bestcem.xm.txtanls.grpc.v1.common.Page;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

/**
 * 分页参数入参校验
 *
 * @author XiaoYunSong <ys.xiao@idiaoyan.com>
 * @version v1.0
 * @date 2021/5/11-16:01
 */
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class PageParam {
    /**
     * 页号
     */
    @NotNull(message = "页号不能为空")
    @Min(value = 0, message = "页号不能小于0")
    private Integer page;

    /**
     * 分页大小
     */
    @NotNull(message = "每页大小不能为空")
    @Min(value = 0, message = "每页大小不能小于0")
    @Max(value = 9999, message = "每页大小不能大于9999")
    private Integer size;


    /**
     * page转换为param使用
     *
     * @param page grpc中page
     * @see Page
     */
    public static PageParam infoToParam(Page page) {
        int defaultIndex = page.getPage();
        int defaultPageSize = page.getSize();
        if (defaultIndex > 0) {
            defaultIndex = page.getPage() - 1;
        }
        return new PageParam(defaultIndex, defaultPageSize);
    }

    public static Page convertToPage(PageParam param) {
        Page.Builder builder = Page.newBuilder();
        builder.setSize(param.getSize());
        builder.setPage(param.getPage() + 1);
        return builder.build();
    }

    /**
     * 原话记录查询每页条数，默认10条（暂定）
     *
     * @return
     */
    public PageParam setRecordDefaultSize() {
        if (this.size < 1) {
            this.setSize(10);
        }
        return this;
    }
}
